import tornado.web
import tornado.ioloop
from tornado.httpclient import AsyncHTTPClient
from . import utils
import json
import threading
'''
#1.5原声同步检索接口
    http://ip:port/receive/aasSyncSearch
    {
        "fileUrl":"",
        "dbCode":"",
        "topNum":0
    }
    resp:
    {
        "state":{
            "ok":1,
            "failed":""
        },
        "result":[]
    }
'''
class receive_aasSyncSearch(tornado.web.RequestHandler):

    async def post(self, *args, **kwargs):
        resp = None
        try:
            data=json.loads(self.request.body)
            print(data)
            paramerror = utils.checkParam(data,{
                "fileUrl":"",
                "dbCode":"",
                "topNum":0
            })
            if paramerror == '': #ok
                mediaurls = data['fileUrl'].split(',')
                for url in mediaurls:
                    http_client = AsyncHTTPClient()
                    response = await http_client.fetch(url)
                    print(response)
                    utils.write2file("aasSyncSearch.raw", response.body)
                    http_client.close()

                resp = {
                    "state":{
                        "ok":1,
                        "failed": ""
                    },
                    "result":[]
                }
            else: #failed
                resp = {
                    "state":{
                        "ok":0,
                        "failed": paramerror
                    },
                    "result":[]
                }

        except BaseException as e:
            resp = {
                "state":{
                    "ok":0,
                    "failed": str(e)
                },
                "result":[]
            }

        self.write(resp)
